import Cookies from 'js-cookie';

/**
 * 用户认证相关的工具函数
 */

// 本地存储键名
const TOKEN_KEY = 'weai_token';
const USER_INFO_KEY = 'weai_user_info';

/**
 * 保存用户令牌到本地存储和Cookie
 * @param token JWT令牌
 */
export const storeToken = (token: string): void => {
  localStorage.setItem(TOKEN_KEY, token);
  Cookies.set(TOKEN_KEY, token, { expires: 1 }); // 1天过期
};

/**
 * 从本地存储中获取用户令牌
 * @returns 存储的JWT令牌或null
 */
export const getStoredToken = (): string | null => {
  return localStorage.getItem(TOKEN_KEY) || Cookies.get(TOKEN_KEY) || null;
};

/**
 * 保存用户信息到本地存储
 * @param userInfo 用户信息对象
 */
export const storeUserInfo = (userInfo: any): void => {
  localStorage.setItem(USER_INFO_KEY, JSON.stringify(userInfo));
};

/**
 * 从本地存储中获取用户信息
 * @returns 解析后的用户信息对象或null
 */
export const getStoredUserInfo = (): any | null => {
  const userInfoStr = localStorage.getItem(USER_INFO_KEY);
  if (userInfoStr) {
    try {
      return JSON.parse(userInfoStr);
    } catch (error) {
      console.error('解析用户信息失败:', error);
      return null;
    }
  }
  return null;
};

/**
 * 清除存储的用户凭证（令牌和用户信息）
 */
export const clearStoredCredentials = (): void => {
  localStorage.removeItem(TOKEN_KEY);
  localStorage.removeItem(USER_INFO_KEY);
  Cookies.remove(TOKEN_KEY);
};

/**
 * 检查用户是否已登录
 * @returns 布尔值，表示用户是否已登录
 */
export const isUserLoggedIn = (): boolean => {
  return !!getStoredToken() && !!getStoredUserInfo();
};

/**
 * 处理登录成功后的认证信息存储
 * @param token JWT令牌
 * @param userInfo 用户信息对象
 */
export const handleSuccessfulAuth = (token: string, userInfo: any): void => {
  storeToken(token);
  storeUserInfo(userInfo);
};

// 兼容旧API
export const getToken = getStoredToken;
export const setToken = storeToken;
export const removeToken = (): void => {
  localStorage.removeItem(TOKEN_KEY);
  Cookies.remove(TOKEN_KEY);
};

export const getUser = getStoredUserInfo;
export const setUser = storeUserInfo;
export const removeUser = (): void => {
  localStorage.removeItem(USER_INFO_KEY);
};

export const isAuthenticated = isUserLoggedIn;
export const logout = clearStoredCredentials; 